package com.taocyb.framework.security.captcha.kaptcha;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.CubicCurve2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.util.Random;

import com.google.code.kaptcha.NoiseProducer;
import com.google.code.kaptcha.util.Configurable;

/**
 * 验证码干扰线
 */
public class DefaultNoise extends Configurable implements NoiseProducer {

    public void makeNoise(BufferedImage image, float factorOne, float factorTwo, float factorThree, float factorFour) {
        Random random = new Random();
        int width = image.getWidth();
        int height = image.getHeight();

        Point2D[] pts = null;

        CubicCurve2D cc = new CubicCurve2D.Float(width * factorOne, height * random.nextFloat(), width * factorTwo,
                height * random.nextFloat(), width * factorThree, height * random.nextFloat(), width * factorFour,
                height * random.nextFloat());

        PathIterator pi = cc.getPathIterator(null, 2);
        Point2D tmp[] = new Point2D[width*8];
        int i = 0;

        while (!pi.isDone()) {
            float[] coords = new float[3];
            switch (pi.currentSegment(coords)) {
            case PathIterator.SEG_MOVETO:
            case PathIterator.SEG_LINETO:
                tmp[i] = new Point2D.Float(coords[0], coords[1]);
            }
            i++;
            pi.next();
        }

        pts = new Point2D[i];
        System.arraycopy(tmp, 0, pts, 0, i);

        Graphics2D graph = (Graphics2D) image.getGraphics();
        graph.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
        for (i = 0; i < pts.length - 1; i++) {
            graph.setColor(KaptchaUtils.getRandColor(140, 190));
            graph.drawOval((int) pts[i].getX(), (int) pts[i].getY(), 1, 1);
            graph.setColor(KaptchaUtils.getRandColor(160, 210));
            graph.drawOval((int) pts[i + 1].getX(), (int) pts[i + 1].getY(), 1, 1);
        }
        graph.dispose();
    }

}